import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, DatePicker, Drawer, Form, FormProps, InputNumber, Select, Space } from 'antd';
import dayjs from 'dayjs';

import { store } from '@/store';

import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  safeChemicalsReportAdd,
  safeChemicalsReportUpdate
} from '@/services/bizApi/anquanweihuapinguanlibaobiaojiekou';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        chargeUserName: userInfo?.data?.filter((item) => item.id === values?.chargeUserId)?.[0]
          ?.fullName
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit'
        ? safeChemicalsReportUpdate(query)
        : safeChemicalsReportAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData,
              dates: arg.rowData.dates ? dayjs(arg.rowData.dates) : undefined
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增',
          edit: '编辑',
          detail: '详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item name="site" label="站点" rules={[{ required: true, message: '请选择站点' }]}>
          <Select
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择站点"
            options={(store.dict['productionSite'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }))}
          />
        </Form.Item>
        <Form.Item
          label="日期"
          name="dates"
          rules={[
            {
              required: true,
              message: '请选择日期'
            }
          ]}
        >
          <DatePicker style={{ width: '100%' }} placeholder="请选择日期" />
        </Form.Item>
        <Form.Item
          label="盐酸入库数量"
          name="ysIn"
          rules={[
            {
              required: true,
              message: '请输入盐酸入库数量'
            }
          ]}
        >
          <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入盐酸入库数量" />
        </Form.Item>
        <Form.Item
          label="盐酸出库数量"
          name="ysOut"
          rules={[
            {
              required: true,
              message: '请输入盐酸出库数量'
            }
          ]}
        >
          <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入盐酸出库数量" />
        </Form.Item>
        <Form.Item
          label="盐酸库存数量"
          name="ysInventory"
          rules={[
            {
              required: true,
              message: '请输入盐酸库存数量'
            }
          ]}
        >
          <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入盐酸库存数量" />
        </Form.Item>
        <Form.Item
          label="硫酸入库数量"
          name="lsIn"
          rules={[
            {
              required: true,
              message: '请输入硫酸入库数量'
            }
          ]}
        >
          <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入硫酸入库数量" />
        </Form.Item>
        <Form.Item
          label="硫酸出库数量"
          name="lsOut"
          rules={[
            {
              required: true,
              message: '请输入硫酸出库数量'
            }
          ]}
        >
          <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入硫酸出库数量" />
        </Form.Item>
        <Form.Item
          label="硫酸库存数量"
          name="lsInventory"
          rules={[
            {
              required: true,
              message: '请输入硫酸库存数量'
            }
          ]}
        >
          <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入硫酸库存数量" />
        </Form.Item>
        <Form.Item
          label="双氧水入库数量"
          name="sysIn"
          rules={[
            {
              required: true,
              message: '请输入双氧水入库数量'
            }
          ]}
        >
          <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入双氧水入库数量" />
        </Form.Item>
        <Form.Item
          label="双氧水出库数量"
          name="sysOut"
          rules={[
            {
              required: true,
              message: '请输入双氧水出库数量'
            }
          ]}
        >
          <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入双氧水出库数量" />
        </Form.Item>
        <Form.Item
          label="双氧水库存数量"
          name="sysInventory"
          rules={[
            {
              required: true,
              message: '请输入双氧水库存数量'
            }
          ]}
        >
          <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入双氧水库存数量" />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
